package com.wy.business.developer.developer.services;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wy.component.easemob.httpclient.apidemo.EasemobIMUsers;
import com.wy.framework.constants.Constants;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.pojos.TSysUserroles;
import com.wy.framework.services.AbstractBaseService;
import com.wy.component.file.FileUtil;
import com.wy.component.security.DescUtil;

/**
 * 项目名称：openportal
 * 类名称：RegistService
 * 类描述：注册
 * 创建人：张旭星
 * 创建时间：2016-3-21 上午11:47:28
 * 修改人：张旭星
 * 修改时间：2016-3-21 上午11:47:28
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version 
 */
@Service
public class RegistService extends AbstractBaseService {

	private static final char[] object = null;
	private static Logger logger = LoggerFactory
			.getLogger(RegistService.class);

	public String saveDeveloper(String useremail, String password, String name,
			String sex, String enterprise_info, String iD, String mobile_phone) throws IOException, ErrorSqlException {
		TSysUserinfo tSysUserinfo = new TSysUserinfo();
		tSysUserinfo.setCreateTime(new Date());
		tSysUserinfo.setEmail(useremail);
		tSysUserinfo.setGender(sex);
		tSysUserinfo.setIdentificationNo(iD);
		tSysUserinfo.setIdentificationTypeCode("0");
		tSysUserinfo.setIsAvailable("1");
		tSysUserinfo.setCompany(enterprise_info);
		tSysUserinfo.setMobile(mobile_phone);
		tSysUserinfo.setNickname(name);
		tSysUserinfo.setOperatorName("system");
		//头像
		tSysUserinfo.setPhotoUrl(genDefaultHeadImg(useremail));
		
		tSysUserinfo.setUserId(useremail);
		tSysUserinfo.setUserName(name);
		tSysUserinfo.setUserPassword(DescUtil.encrypt(password));
		tSysUserinfo.flushUpdateTime();
		dataBaseDao.save(tSysUserinfo);
		
		// 保存用户角色信息
		TSysUserroles userRoles = new TSysUserroles();
		userRoles.setRoleId(Constants.APP_DEVELOPER);
		userRoles.setUserId(tSysUserinfo.getUserId());
		userRoles.setOperatorAccount("admin");
		userRoles.setOperatorName("system");
		userRoles.setUserRoleId(UUID.randomUUID().toString());
		userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
		userRoles.flushUpdateTime();
		dataBaseDao.save(userRoles);
		
		registIMUser(tSysUserinfo.getUserId(),tSysUserinfo.getUserName() + "_APP开发者");
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}
	
	/**
	 * Function Name               genDefaultHeadImg                                             		             
	 * @param useremail 
	 * @return 
	 * @throws IOException 
	 * @description 新注册用户设置默认头像
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-4-5 下午4:40:40           张旭星                     Initial
	 **********************************************************************
	 */
	public String genDefaultHeadImg(String useremail) throws IOException {
		int number = new Random().nextInt(20) + 1;
		URL url = this.getClass().getClassLoader().getResource("/");
		String pathRoot = url.getPath().replace("/WEB-INF/classes", ""); // 真实路径
		String sourceimgName = "headImg_" + number + ".jpg";
		String Source = pathRoot + "/resources/img/headImg/" + sourceimgName;
		String targetimgName = useremail + ".jpg";
		String pathBody = "/upload/headImg/" + targetimgName;
		String target = pathRoot + pathBody;
		FileUtil.copyFile(new File(Source), new File(target));
		return pathBody;
	}
	
	/**
	 * Function Name               registIMUser                                             		             
	 * @param nickname 
	 * @param userid 
	 * @description 环信注册IM用户[单个]
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-4-5 下午4:53:34           张旭星                     Initial
	 **********************************************************************
	 */
	public void registIMUser(String userid, String nickname) {
		ObjectNode datanode = JsonNodeFactory.instance.objectNode();
		datanode.put("username",EasemobIMUsers.convertUsernameForDeveloper(userid));
		datanode.put("nickname",nickname);
		datanode.put("password", Constants.DEFAULT_PASSWORD);
		ObjectNode createNewIMUserSingleNode = EasemobIMUsers.createNewIMUserSingle(datanode);
//		if (null != createNewIMUserSingleNode) {
//			logger.info("注册IM用户[单个]: " + createNewIMUserSingleNode.toString());
//		}
	}

	public String getJudgeUserId(String useremail) throws ErrorSqlException {
		TSysUserinfo tSysUserinfo = (TSysUserinfo) dataBaseDao.load(TSysUserinfo.class, useremail);
		if(tSysUserinfo!=null)
			return "账号已注册！";
		return "true";
	}

}
